package com.zp.servlet;

import com.google.gson.Gson;
import com.zp.common.ResultEnum;
import com.zp.dao.UserDao;
import com.zp.dao.impl.UserDaoImpl;
import com.zp.dao.impl.UserDaoRaw;
import com.zp.domain.User;
import com.zp.utils.Base64Util;
import com.zp.utils.CookieUtil;
import com.zp.utils.MD5Util;
import com.zp.utils.ResultUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {

	private UserDao userDao;
	private PrintWriter out;

	@Override
	public void init() throws ServletException {
		userDao = new UserDaoImpl();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");

		out = response.getWriter();
		Gson gson = new Gson();

		// 获取发送来的用户名和密码
		String sno = request.getParameter("sno");
		String password = request.getParameter("password");
		// 进行MD5加密
		password = MD5Util.getMD5(password);

		try {
			// 根据学号从数据库获取用户
			User user = userDao.getUserBySno(sno);

			if(user == null) {
				// 用户不存在
				out.print(gson.toJson(ResultUtil.error(ResultEnum.USER_NOT_EXIST.getCode(), ResultEnum.USER_NOT_EXIST.getMsg())));
				return;
			}
			// 获取数据库存储的密文
			String check = Base64Util.getDecoderBase64(user.getPassword());
			if(check.equals(password)) {
				// 登录成功
				// Session存储
				HttpSession session = request.getSession();
				session.setAttribute("CURRENT_USER", user.getSno());
				// Cookie存储
				Cookie[] cookies = request.getCookies();
				Cookie cookie = CookieUtil.findCookie(cookies, "lastLogin");
				String loginTime = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss").format(new Date());
				if (cookie == null) {
					cookie = new Cookie("lastLogin", loginTime);
				} else {
					cookie.setValue(loginTime);
				}
				// 设置cookie路径
				cookie.setPath("/");
				// 生存周期，暂定十分钟
				cookie.setMaxAge(60 * 10);
				response.addCookie(cookie);
				out.print(gson.toJson(ResultUtil.success()));
			}else{
				// 密码错误
				out.print(gson.toJson(ResultUtil.error(ResultEnum.PWD__ERROR.getCode(), ResultEnum.PWD__ERROR.getMsg())));
			}
			return;
		} catch (Exception e) {
			e.printStackTrace();
			out.print(gson.toJson(ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(), ResultEnum.UNKNOWN_ERROR.getMsg())));
		}

	}

	@Override
	public void destroy() {
		// 关闭资源,close源码会自动检测是否为空
		try {
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
